import { HTTP } from '../utils/http-p.js'

class KeywordModel extends HTTP{
  key = 'q'
  maxLength = 10

  /**
   * 获取历史关键字
   * 注：从本地的storage 缓存中获取
   */
  getHistory() {
    const words = wx.getStorageSync(this.key)
    return words || []
  }

  /**
   * 获取热门关键字
   */
  getHot() {
    return this.request({
      url:'/book/hot_keyword'
    })
  }

  /**
   * 将搜索关键字添缓存到本地
   * 每次最多缓存(maxLength),超出的将栈顶的元素移除
   */
  add2History(keyword) {
    let words = this.getHistory()
    const has = words.includes(keyword)
    if (!has) {
      const length = words.length
      if(length >= this.maxLength) {
        words.pop()
      }
      words.unshift(keyword)
      wx.setStorageSync(this.key, words)
    }
  }
}

export { KeywordModel }